<?php

class LoginForm extends CFormModel {

    public $username;
    public $password;
    public $rememberMe;
    public $verifyCode;
    private $_identity;
    public $hiddenCaptcha = true;

    public function rules() {
        return array(
            array('verifyCode', 'captcha',
                'allowEmpty' => $this->hiddenCaptcha
            ),
            array('username, password', 'required',
                'message' => Yii::t('msg', 'please_input')
            ),
            array('password', 'authenticate'),
            array('rememberMe', 'boolean'),
        );
    }

    public function attributeLabels() {
        return array(
            'username'   => 'User name',
            'password'   => 'Password',
            'verifyCode' => 'Verification code',
        );
    }

    public function init() {
        $session = new CHttpSession();
        if (! isset($session['count_login'])) {
            $session['count_login'] = 0;
        }

        if ($session['count_login'] > 2) {
            $this->hiddenCaptcha = false;
        }
    }

    public function authenticate($attribute, $params) {
        if (!$this->hasErrors()) {
            $session = new CHttpSession();
            $this->_identity = new UserIdentity($this->username, $this->password);

            if ( $this->_identity->authenticate() ) {
                if ($this->_identity->errorCode == 1) {
                    $this->addError('username', Yii::t('AuthModule.msg', 'not_exist', array(
                            '{0}' => 'User name',
                            )
                        ));
                } elseif ($this->_identity->errorCode == 2) {
                    $this->addError('password', Yii::t('AuthModule.msg', 'was_incorret', array(
                            '{0}' => 'Password',
                            )
                        ));
                }

                $session['count_login'] = $session['count_login'] + 1;
                if ($session['count_login'] == 3) {
                    $this->hiddenCaptcha = false;
                }
            } else {
                $session->remove('count_login');
            }
        }
    }

    /**
     * Logs in the user using the given username and password in the model.
     * @return boolean whether login is successful
     */
    public function login() {
        if ($this->_identity === null) {
            $this->_identity = new UserIdentity($this->username, $this->password);
            $this->_identity->authenticate();
        }
        if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
            $sessionTimeout = Yii::app()->getSession()->timeout;
            $duration = $this->rememberMe ? 3600 * 24 * 30 : $sessionTimeout;
            Yii::app()->user->login($this->_identity, $duration);

            return true;
        }
        else
            return false;
    }

}